package homework.level01model04.homework03;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Homework03 {

    public static void copyDirectory(String path1,String path2,int index){

        //整个目录复制
        File f1 = new File(path1);
        File f2 = new File(path2);
        /*System.out.println(f1.getName());
        System.out.println(f2.getName());*/
        //判断要复制的目录是否存在
        if (!(f1.exists())){
            System.out.println("要复制的目录不存在");
            return;
        }
        else{
            if (!(f2.exists())){
                //System.out.println("被复制的目录不存在");
                f2.mkdir();
                /*System.out.println("创建一个目录存储被复制文件");
                System.out.println(f2);
                System.out.println(f2.getName());*/
            }else{   //目录都已备好 开始进行复制
                //创建一个线程池
                ExecutorService executorService = Executors.newFixedThreadPool(10);

                File[] files = f1.listFiles();
                for (File file : files) {
                    executorService.submit(() ->{

                        if (file.isFile()){
                            //如果目录中元素为文件
                            //父路径为file的路径 子 路径为path2+\\+file.getNmae();
                            copyFile(file.getAbsolutePath(),path2+"\\"+file.getName());

                        }
                        else{
                            //如果目录中的元素还是目录
                            copyDirectory(file.getAbsolutePath(),path2+"\\"+file.getName(),index);

                        }
                        System.out.println(file.getName());

                    });

                }
                executorService.shutdown();
            }
        }



    }




    public static void copyFile(String path1,String path2){

        //创建流
        BufferedWriter bw = null;
        BufferedReader br = null;
        try {
             bw = new BufferedWriter(new FileWriter(path2));
             br = new BufferedReader(new FileReader(path1));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //读出和写入
        String str = null;
        try {
            while( ( str=br.readLine())!=null){
                bw.write(str);
                bw.newLine();
                System.out.println("复制成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                if (null != bw){
                    bw.close();
                }
                if (null != bw){
                    br.close();
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
